
<%@ page contentType="text/html; charset=utf-8" 
%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" 
%><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" 
%><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" 
%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>fileupload-basic.jsp</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
    body {
        font-size: 12px;
        font-family: Lucida Grande,Lucida Sans,Arial,sans-serif;
    }
    
    [css-tag=button] {
        width: 19px !important;
        height: 20px !important;
    }
    
    [css-tag=span-file] {
        line-height: 25px;;
        display: block;
    }
    
    .file-upload-button {
        display: inline-block;
        padding:6px 12px;
        color: #fff;
        background-color: #5cb85c;
        border-color: #4cae4c;
    }
    
    .file-upload-button:hover {
        background-color: #47a447;
        border-color: #398439;
    }
</style>
<script src="${pageContext.request.contextPath}/js/jquery/jquery-1.11.0.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/js/jquery/ui/css/redmond/jquery-ui-1.10.4.custom.css" />
<script src="${pageContext.request.contextPath}/js/jquery/ui/js/jquery-ui-1.10.4.custom.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery/file-upload/js/vendor/jquery.ui.widget.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery/file-upload/js/jquery.iframe-transport.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/js/jquery/file-upload/js/jquery.fileupload.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/js/jquery/file-upload/css/jquery.fileupload.css" />
<c:set value="${pageContext.request.contextPath}/app/file/upload" var="fileUploadUrl"/>
<script type="text/javascript">
var files = [
    {name:"첫번째 파일.txt", newName:"dgadfaf.txt", size:1500, ext:"txt"},
    {name:"두번째 파일.jpg", newName:"dgadfaf.jpg", size:45500, ext:"jpg"},
    {name:"세번째 파일.xls", newName:"dgadfaf.xls", size:1800, ext:"xls"}
];

$(function () {
	init("div-file");
	
    $("#fileupload").fileupload({
        add: function(e, data) {
            var isOK = true;
            
            if (data.files.length > 0) {
                var size = data.files[0].size;
                if (!size && size >= 5000000) { alert("파일크기가 초과되었습니다."); return; }
            }
            
            var list = $div.data("file-list");
            for (var i = 0; list && i < list.length; i++) {
            	if (list[i].file.name == data.files[0].name && $.inArray(list[i].tp, ["old", "new"]) > -1) { alert("동일한 이름의 파일이 이미 선택되었습니다."); return; }
            }
            
            data.submit(); 
        },    	
        url: "${fileUploadUrl}",
        dataType: "text",
        done: function (e, data) {
        	if (data.result) {
	            var jsonData = $.parseJSON(data.result);
	            
	            if (jsonData.state && jsonData.state == "fail") {
	            	alert(jsonData.message);
	            } else {
		            $.each(jsonData, function (index, file) {
		            	addFileDesc(file, "new")
		            })
	            };
        	} else {
                alert("처리 중 오류가 발생하였습니다.");
        	}
        },
        /* progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }, */
        fail: function(e, data) {
            if (data.jqXHR.responseText) {
            	var result = $.parseJSON(data.jqXHR.responseText);
                alert(result.message); 
            } else {
                alert("처리 중 오류가 발생하였습니다.");
            }
        }	        
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
    
    for (var i = 0; files && i < files.length; i++) {
    	addFileDesc(files[i], "old");
    }
    
    $("#attach").click(function () {
        $("#fileupload").trigger("click");
    });    
});	

var $div;

function init(elemId) {
	$div = $("#" + elemId);
//  $div.append("<span class='btn btn-success fileinput-button'><span>Select files...</span><input id='fileupload' type='file' name='file' multiple style='opacity: 0; filter:alpha(opacity: 0);'/></span><br/><span id='filename'></span>");
// 	$div.append("<a href='#' id='attach'>파일선택</a><input id='fileupload' type='file' name='file' multiple style='opacity: 0; filter:alpha(opacity: 0);'><br/><span id='filename'/>");
	$div.append("<span class='btn btn-success fileinput-button'><label for='fileupload' style='cursor:pointer'>파일선택...</label><input id='fileupload' type='file' name='file'/></span><br/><span id='filename'></span>");
	$div.data("file-list", []);
}

function getFileHtml(file) {
    var html = "<span class='ui-widget' css-tag='span-file' data-tag='file' id='{new.name}'>{file}&nbsp;({size}K)&nbsp;"
        + "<button class='ui-button ui-widget ui-state-default ui-corner-all' css-tag='button'><span class='ui-icon ui-icon-closethick'/></button>"
        + "</span>";
        
    html = html.replace("{new.name}", file.newName).replace("{file}", file.name).replace("{size}", (file.size / 1000).toFixed(2));
    return html;
}

function addFileDesc(file, tp) {
    var $elem = $(getFileHtml(file));
    var data = $div.data("file-list");
    data.push({tp:tp, file:file});
    
    $elem.find("[css-tag='button']").bind("click", function() {
    	var newName = $elem.attr("id");
    	
    	var data = $div.data("file-list");
    	var tp = "";
    	for (var i = 0; data && i < data.length; i++) {
    		if (data[i].file.newName == newName) {
    			if (data[i].tp == "new") {
    			    tp = "del.new";    				
    			} else
    			if (data[i].tp == "old") {
    				tp = "del.old";
    			}
    			data.push({tp:tp, file:data[i].file});
    			if (data[i].tp == "new") {
					data.splice(i, 1);    				
    			}
    			break;
    		} 
    	}
    	
        $(this).parent().remove(); // 업로드 파일 정보를 삭제한다.
    });
    $("#filename").append($elem);
}
</script>
</head>
<body>
<%--
<div id="file">
    <span class="btn btn-success fileinput-button">
    	<i class="glyphicon glyphicon-plus"></i>
        <span>Select files...</span><input id="fileupload" type="file" name="file" multiple>
    </span><br/>
    <span id="filename"></span>
</div>
--%>
<table>
<tr><td>컬럼1</td><td>컬럼2</td></tr>
<tr><td></td><td>
<div id="div-file"><%--
    <span class="btn btn-success fileinput-button">
        <label for="fileupload">파일선택...</label><input id="fileupload" type="file" name="file" multiple>
    </span><br/>
    <span id="filename"></span>
--%></div>
</td></tr>
</table>
</body>
</html>